<?

class Mojito_View_Helper_JsInit extends Zend_View_Helper_Abstract
{
	/**
	 * methodStack
	 * Stores methods to be called
	 * (default value: array())
	 * 
	 * @var array
	 * @access private
	 */
	private $methodStack=array();
	
	/**
	 * __set function.
	 * 
	 * @access public
	 * @param mixed $name
	 * @param mixed $value
	 * @return void
	 */
	public function __set($name, $value)
	{
		throw new Exception('__set() is not allowed, please use addMethod() instead.');
	}
	
	/**
	 * __get function.
	 * 
	 * @access public
	 * @param mixed $name
	 * @return void
	 */
	public function __get($name)
	{
		throw new Exception('__get() is not allowed.');
	}
	
	/**
	 * addMethod function.
	 * 
	 * @access public
	 * @return void
	 */
	public function addMethod($method,$data=null)
	{
		if (is_object($data)) throw new Exception('Method data must not be of type object. Please use associative array instead.');
		$this->methodStack[]=array('method'=>$method,'data'=>$data);
		return $this;
	}
	
	/**
	 * hasMethod function.
	 * 
	 * @access public
	 * @param mixed $method
	 * @return boolean
	 */
	public function hasMethod($method)
	{
		return array_key_exists($method,$this->methodStack);
	}
	
	/**
	 * reset the method stack to 0 methods.
	 * 
	 * @access public
	 * @return void
	 */
	public function clearMethods()
	{
		$this->methodStack=array();
		return $this;
	}
	
	/**
	 * JsInit function.
	 * 
	 * @access public
	 * @return string
	 */
	public function JsInit()
	{
		$out='';
		if (!empty($this->methodStack))
		{
			$out='<script type="text/javascript">(function(){';
			$count=0;
			foreach($this->methodStack as $item) 
			{
				$out.="\r\n".$item['method'].'(';
				if (!empty($item['data'])) $out.=(is_array($item['data'])?Zend_Json::encode($item['data'],true,array('enableJsonExprFinder'=>true)):(is_string($item['data'])?"'".addslashes($item['data'])."'":$item['data']));
				$out.=');';
			}
			$out.="\r\n".'})()</script>';
		}
		return $out;
	}
}